﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace sdd.apps
{
    public class ApplicationManager
    {
        private List<IApplication> _Apps;
        public Director Director { set; get; }

        public ApplicationManager()
        {
            _Apps = new List<IApplication>();
        }

        ~ApplicationManager()
        {
            UnloadAll();
            _Apps = null;
        }

        public IApplication Application(string appName)
        {
            foreach (IApplication app in _Apps)
            {
                if (app.Name == appName) { return app; }
            }
            return null;
        }

        public void Load(string assemblyName, string typeName)
        {
            var dirSep = System.IO.Path.DirectorySeparatorChar;
            string assemblyPath = Environment.CurrentDirectory + dirSep + assemblyName + ".dll";
            AppDomain.CurrentDomain.Load(System.IO.File.ReadAllBytes(assemblyPath));
            IApplication newApp = (IApplication)(Activator.CreateInstance(assemblyName, "sirp.apps." + typeName).Unwrap());
            newApp.Director = Director;
            _Apps.Add(newApp);
            newApp.Initialize();
        }

        public void Unload(IApplication appToUnload)
        {
            appToUnload.Deactivate();
            appToUnload.Terminate();
            appToUnload.Director = null;
            _Apps.Remove(appToUnload);
        }

        public void UnloadAll()
        {
            foreach (IApplication app in _Apps)
            {
                app.Deactivate();
                app.Terminate();
                app.Director = null;
            }
            _Apps.Clear();
        }

    }
}
